/**
 * @author Teacher Gong
 * @note 主界面
 */

package team.wh1tegive.cg;

import team.wh1tegive.misc.Log;
import team.wh1tegive.user.CashFlow;
import team.wh1tegive.user.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class MainFrame extends JFrame implements ActionListener {
    private JMenuBar mb = new JMenuBar();
    private JMenu m_system = new JMenu("系统管理");
    private JMenu m_fm = new JMenu("收支管理");
    private JMenuItem mI[] = {new JMenuItem("密码重置"), new JMenuItem("退出系统")};
    private JMenuItem m_FMEdit = new JMenuItem("收支编辑");
    private JLabel l_type, l_fromdate, l_todate, l_bal, l_ps;
    private JTextField t_fromdate, t_todate;
    private JButton b_select1, b_select2;
    private JComboBox c_type;
    private JPanel p_condition, p_detail;
    private String s1[] = {"收入", "支出"};
    private double bal1, bal2;
    private JTable table;
    private String username;
    private User user;
    int i;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");

    public MainFrame(String username) {
        super(username + ",欢迎使用个人理财账本!");
        this.username = username;
        this.user = new User(username);
        Container c = this.getContentPane();
        c.setLayout(new BorderLayout());
//北布局("系统管理","收支管理")
        c.add(mb, "North");
        mb.add(m_system);
        mb.add(m_fm);
//系统管理里面增加"密码重置","退出系统"
        m_system.add(mI[0]);
        m_system.add(mI[1]);
//收支管理加入"收支编辑"
        m_fm.add(m_FMEdit);

        m_FMEdit.addActionListener(this);
        mI[0].addActionListener(this);
        mI[1].addActionListener(this);
//收支类型面板布局
        l_type = new JLabel("收支类型：");
        c_type = new JComboBox(s1);//JComboBOX下拉列表组件:"收入","支出"
        b_select1 = new JButton("查询");
        l_fromdate = new JLabel("起始时间");
        t_fromdate = new JTextField(8);
        l_todate = new JLabel("终止时间");
        t_todate = new JTextField(8);
        b_select2 = new JButton("查询");
        l_ps = new JLabel("注意：时间格式为YYYYMMDD，例如：20150901");
        p_condition = new JPanel();
        p_condition.setLayout(new GridLayout(3, 1));//输入查询条件面板为3行1列的布局
        p_condition.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("输入查询条件"),
                BorderFactory.createEmptyBorder(5,5 , 5, 5)));

        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        //第一行放置:"收入类型","支出","查询"
        p1.add(l_type);
        p1.add(c_type);
        p1.add(b_select1);
        //第二行放置:"起始时间","文本框","终止时间","文本框","查询"
        p2.add(l_fromdate);
        p2.add(t_fromdate);
        p2.add(l_todate);
        p2.add(t_todate);
        p2.add(b_select2);
        //第三行放置提示时间格式标签
        p3.add(l_ps);

        p_condition.add(p1);
        p_condition.add(p2);
        p_condition.add(p3);

        c.add(p_condition, "Center");//"输入查询条件模块设置为'中'"

        b_select1.addActionListener(this);
        b_select2.addActionListener(this);
//收支明细信息面板布局
        p_detail = new JPanel();
        p_detail.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("收支明细信息"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        l_bal = new JLabel();
        //表格
        String[] cloum = {"编号", "日期", "类型", "内容", "金额",};
        Object[][] row = new Object[50][5];
        table = new JTable(row, cloum);
        JScrollPane scrollpane = new JScrollPane(table);
        scrollpane.setPreferredSize(new Dimension(580, 350));//表格大小布局
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setViewportView(table);

        p_detail.add(l_bal);
        p_detail.add(scrollpane);
        c.add(p_detail, "South");//收支明细布局设置为"南"

        //添加代码


        this.setResizable(false);
        this.setSize(600, 580);
        Dimension screen = this.getToolkit().getScreenSize();
        this.setLocation((screen.width - this.getSize().width) / 2, (screen.height - this.getSize().height) / 2);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                Log.writeLog(username + " Exited the Application.");
            }
        });
        bal1 = user.getBalance();
        if (bal1 < 0)
            l_bal.setText("个人总收支余额为" + bal1 + "元。您已超支，请适度消费！");
        else
            l_bal.setText("个人总收支余额为" + bal1 + "元。");
    }

    public void actionPerformed(ActionEvent e) {
        Object temp = e.getSource();
        if (temp == mI[0]) {
            new ModifyPwdFrame(this.user);
        } else if (temp == mI[1]) {
            Log.writeLog(username + " Exited the Application.");
            System.exit(0);
        } else if (temp == m_FMEdit) {
            new BalEditFrame(this.user);
        } else if (temp == b_select1) {
            Clear();
            Balance();//余额刷新
           String type= c_type.getSelectedItem().toString().trim();
            try {
                i=0;
                ArrayList<CashFlow> cfl = user.UAtypeSelect(type);
                for (CashFlow cf : cfl) {
                    addRow(cf, i++);
                }
                JOptionPane.showMessageDialog(null, "查询所有收支信息成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                Log.writeLog(" Successfully Select * from UserAction by 收支/支出.");
            } catch (Exception exception) {
                Log.writeError("Check record failed by income/outcome.");
            }


        } else if (temp == b_select2) { // 根据时间范围查询
            Clear();
            Balance();
            if (CheckTimeInput()) {

                try {
                    int i = 0;
                    int begin = Integer.parseInt(t_fromdate.getText());
                    int end = Integer.parseInt(t_todate.getText());
                    ArrayList<CashFlow> cfl = user.UASelect();
                    for (CashFlow cf : cfl) {
                        int tempDate = Integer.parseInt(cf.date);
                        if (tempDate >= begin && tempDate <= end)
                            addRow(cf, i++);
                    }
                    JOptionPane.showMessageDialog(null, "根据时间查询所有收支信息成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    Log.writeLog(" Successfully Select * from UserAction by 起始时间/终止时间.");
                } catch (Exception exception) {
                    Log.writeError("Check record failed by time. Got Illegal Time");
                }
            }
        }
    }
    public void addRow(CashFlow cf, int i) {
        table.getModel().setValueAt(cf.actionId, i, 0);
        table.getModel().setValueAt(cf.date, i, 1);
        table.getModel().setValueAt(cf.isInCome, i, 2);
        table.getModel().setValueAt(cf.info, i, 3);
        table.getModel().setValueAt(cf.amount, i, 4);
    }
    public void Clear() {
        for (int j = 0; j < 50; j++) {
            table.getModel().setValueAt("", j, 0);
            table.getModel().setValueAt("", j, 1);
            table.getModel().setValueAt("", j, 2);
            table.getModel().setValueAt("", j, 3);
            table.getModel().setValueAt("", j, 4);
        }
    }
    public void Balance(){
        bal1 = user.getBalance();
        if (bal1 < 0)
            l_bal.setText("个人总收支余额为" + bal1 + "元。您已超支，请适度消费！");
        else
            l_bal.setText("个人总收支余额为" + bal1 + "元。");
    }
    public boolean CheckTimeInput() {
        try {
            Date date1 = sdf.parse(t_fromdate.getText());
            Date date2 =sdf.parse(t_todate.getText());
        } catch (ParseException e) {
            Log.writeError("Time Format Error.");
            JOptionPane.showMessageDialog(null, "输入时间格式错误，请重新输入", "警告", JOptionPane.ERROR_MESSAGE);
            t_fromdate.setText("");
            t_todate.setText("");
            return false;
        }
        return true;
    }
}